const Koa = require('koa')
const router = require('koa-router')()
const render = require('koa-art-template')
const path = require('path')
const db = require('./module/db')
const bodyParser = require('koa-bodyparser')
const static = require('koa-static')

// 实例化
const app = new Koa()

// 配置中间件
app.use(bodyParser()) //配置post bodyparser中间件
app.use(static('static')) //配置静态资源中间件

// 配置art模板引擎
render(app, {
  root: path.join(__dirname, 'views'), //视图的位置
  extname: '.html', //后缀名 
  debug: process.env.NODE_ENV !== 'production' //是否开启调试模式
})


//路由配置
router.get('/', async (ctx) => {

  console.time('time')
  const result = await db.find('user', {})
  // console.log(result)
  console.timeEnd('time')

  await ctx.render('index', {
    list: result
  })
})

router.get('/add', async (ctx) => {
  await ctx.render('add')
})

router.post('/doAdd', async (ctx) => {
  try {
    const body = ctx.request.body
    const { result } =await db.insert('user', {
      ...body, 
      age: Number.parseInt(body.age)
    })
    if (result.ok) {
      ctx.redirect('/')
    }
  } catch (error) {
    console.log(error)
    ctx.redirect('/add')
  }
    
})

router.get('/edit', async (ctx) => {

  const id = ctx.query.id
  const data = await db.find('user', { _id: db.getObjectId(id) }) 
  console.log(data)
  await ctx.render('edit', {
    data: data[0]
  })

})

router.post('/doEdit', async (ctx) => {

  const id = ctx.request.body.id
  const name = ctx.request.body.name
  const age = Number.parseInt(ctx.request.body.age)
  const sex = ctx.request.body.sex

  try {
    const {result} = await db.update('user', { _id: db.getObjectId(id)}, { name, age, sex }) 
    if (result.ok) {
      ctx.redirect('/')
    }
  } catch (error) {
    ctx.redirect('/')
  } 

})

router.get('/delete', async (ctx) => {

  const id = ctx.query.id
  try {
    const {result} = await db.remove('user', { _id: db.getObjectId(id) }) 

    if(result.ok) {
      ctx.redirect('/')
    }
  } catch (error) {
    console.log(error)
    ctx.redirect('/')
  }
  
})

//启动路由
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)